package com.chuck.blogpro.service.impl;

import com.chuck.blogpro.mapper.ArticleMapper;
import com.chuck.blogpro.pojo.Article;
import com.chuck.blogpro.pojo.PageBean;
import com.chuck.blogpro.service.ArticleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Article getArticleById(Integer id) {
        return articleMapper.getArticleById(id);
    }

    @Override
    public PageBean page(Integer page, Integer pageSize) {
//        // 获取总记录数:自己写法
//        Long total = articleMapper.getTotal();
//        // 获取起始索引
//        Integer startIndex = (page - 1) * pageSize;
//        // 获取当前页数据
//        List<Article> rows = article Mapper.page(startIndex, pageSize);
//        return new PageBean(rows, total);
        // 使用 pageHelper 写法
        // 1. 添加分页
        PageHelper.startPage(page, pageSize);
        // 2. 获取数据
        List<Article> list = articleMapper.list();
        Page<Article> pageInfo = (Page<Article>) list;
        log.info("pageInfo: {}", pageInfo);
        // 3. 返回数据
        return new PageBean(pageInfo.getResult(), pageInfo.getTotal());
    }

    @Override
    public void add(Article article) {
        articleMapper.add(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }
}
